#http://acad.cnki.net/KNS/brief/result.aspx?dbprefix=CDFD
from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re
import time

#每次拿去最新的cookies
def updateCookie(cookies,tempCookies):

    for k, v in tempCookies.items():
        cookies[k] = v

    return cookies

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data


def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    trs = soup.select(".GridTableContent > tbody > tr")[1:]

    for tr in trs:

        tempData = resultData()

        try:
            tempData["titleName"] = tr.select("a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = tr.select("a")[0]["href"]
        except:
            pass

        allData.append(tempData)

    return allData

def buildingParameters(data):
    # 主题、题名或关键词、题名、第一作者、作者单位、作者、关键词、摘要、基金、DOI
    # 主题:()*作者:()
    typeCorr = {
        "SU": "主题",
        "TI": "题名",
        "AU": "作者",
        "AF": "作者单位",
        "AB": "摘要",
        "KY": "关键词",
    }
    logCorr = {
        "and": "*",
        "or": "+",
        "not": "^",
        "###":"###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            strr = typeCorr[data["type"][i]] + ":" + "(" + data["values"][i] + ")" + "{}".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            continue

    strr = ''
    for value in tempStr:
        strr += value

    return strr.strip().strip("#").strip()


def getData(keyword,cookies,url):


    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://acad.cnki.net/KNS/brief/result.aspx?dbPrefix=SCSF',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    t = time.time()

    rootU = "http://acad.cnki.net/KNS/brief/brief.aspx?pagename={}&t={}&keyValue={}&S=1".format(url,int(round(t * 1000)),keyword)


    response = requests.get(rootU, headers=headers,cookies = cookies)

    result= formData(response)


    return result

def getCookies(keyword,cookies):
    headers = {
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': '*/*',
        'Referer': 'http://acad.cnki.net/KNS/brief/result.aspx?dbprefix=CDFD',
        'Connection': 'keep-alive',
    }

    params = (
        ('txt_1_sel','SU'),
        ('txt_1_value1',keyword),
        ('action', ''),
        ('NaviCode', '*'),
        ('ua', '1.21'),
        ('PageName', 'ASP.brief_result_aspx'),
        ('DbPrefix', 'CDFD'),
        ('DbCatalog', '\u4E2D\u56FD\u535A\u58EB\u5B66\u4F4D\u8BBA\u6587\u5168\u6587\u6570\u636E\u5E93'),
        ('ConfigFile', 'CDFD.xml'),
        ('db_opt', '\u4E2D\u56FD\u535A\u58EB\u5B66\u4F4D\u8BBA\u6587\u5168\u6587\u6570\u636E\u5E93'),
        ('db_value', '\u4E2D\u56FD\u535A\u58EB\u5B66\u4F4D\u8BBA\u6587\u5168\u6587\u6570\u636E\u5E93'),
        ('his', '0'),
        ('__', 'Fri Feb 22 2019 10:40:31 GMT+0800 (\u4E2D\u56FD\u6807\u51C6\u65F6\u95F4)'),
    )
    s = requests.session()
    response = s.get('http://acad.cnki.net/KNS/request/SearchHandler.ashx', headers=headers, params=params,cookies = cookies)

    cookies = s.cookies.get_dict()

    return cookies,response.text

def getOneCookies():

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('dbPrefix', 'SCSF'),
    )
    s = requests.session()

    response = s.get('http://acad.cnki.net/KNS/brief/result.aspx', headers=headers, params=params)

    cookies = s.cookies.get_dict()

    return cookies


def index(request):
    data = json.loads(request.POST.get('data', '1'))

    cookies = getOneCookies()

    cookiesT,url = getCookies(data["values"][0],cookies)

    cookies = updateCookie(cookies,cookiesT)

    data = getData(data["values"][0],cookies,url)

    return HttpResponse(json.dumps({
        "collection": data,
        "allNum": 0
    }), content_type="application/json")

